/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.jit.core.compile;

import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Kaixuan Shi
 * @since 2023/7/7
 */
public class JitJavaFileManager extends ForwardingJavaFileManager<JavaFileManager> {

    //存放编译后的class
    private final Map<String, BytesJavaFileObject> outputJavaFileObjectMap = new ConcurrentHashMap<>();

    //存放编译后的类名及其对应的内部class的类名
    private final List<String> innerClassNames = new ArrayList<>();

    //返回类及其内部类
    public List<BytesJavaFileObject> getCompiledJavaFileObject(String className) {
        List<BytesJavaFileObject> fileObjects = new ArrayList<>();
        BytesJavaFileObject bytesJavaFileObject = outputJavaFileObjectMap.get(className);
        if (bytesJavaFileObject != null) {
            fileObjects.add(bytesJavaFileObject);
            innerClassNames.forEach(innerClassName -> {
                if (innerClassName.startsWith(className)) {
                    fileObjects.add(outputJavaFileObjectMap.get(innerClassName));
                }
            });
        }
        return fileObjects;
    }

    public JitJavaFileManager(JavaFileManager fileManager) {
        super(fileManager);
    }

    /**
     * 这里是编译器返回的同(源)Java文件对象,替换为StringJavaFileObject实现
     */
    @Override
    public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling) {
        BytesJavaFileObject javaFileObject = new BytesJavaFileObject(className, kind);
        outputJavaFileObjectMap.put(className, javaFileObject);
        if (className.contains("$")) {
            innerClassNames.add(className);
        }
        return javaFileObject;
    }

}
